<template>
  <el-form-item :prop="field" :rules="[
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator: checkMobile, trigger: 'change,blur' },
            { validator: uniqueMobile, trigger: 'change,blur' }
          ]" ref="mobileInput" label="手机号">
    <el-input placeholder="请输入手机号" v-model="currentValue">
      <!--<template slot="append">-->
        <!--<i class="el-icon-mobile-phone"></i>-->
      <!--</template>-->
      <el-button slot="append" @click="getVCode" :disabled="!isValid" style="width: 128px">{{sendButtonText}}</el-button>
    </el-input>
  </el-form-item>
</template>
<script>
import { checkMobile, uniqueMobile } from "libs/checkRules";

export default {
  props: {
    field: String,
    value: String
  },
  created() {
    this.currentValue = this.value;
  },
  mounted() {
    this.$watch("$refs.mobileInput.validateState", val => {
      this.validateState = val;
    });
  },
  data() {
    return {
      currentValue: "",
      checkMobile: checkMobile,
      uniqueMobile: uniqueMobile,
      sendButtonText: "获取验证码",
      countdown: 0,
      validateState: ""
    };
  },
  computed: {
    isValid() {
      return this.validateState === "success";
    }
  },
  watch: {
    value(val) {
      this.currentValue = val;
    },
    currentValue(val) {
      this.$emit("input", val);
    }
  },
  methods: {
    getVCode() {
      if (this.countdown === 0) {
        this.countdown = 30;
        const timeoutMS = 1000;
        this.sendButtonText = "请稍后(" + this.countdown + "秒)";
        const cd = setInterval(() => {
          this.countdown--;
          this.sendButtonText = "请稍后(" + this.countdown + "秒)";
          if (this.countdown === 0) {
            clearInterval(cd);
            this.sendButtonText = "获取验证码";
          }
        }, timeoutMS);

        this.$store.dispatch("getVcode", this.currentValue).then(ret => {
          this.$emit("vcode-callback", ret);
        });
      }
    }
  },
  components: {}
};
</script>
<style>
</style>
